package com.minelx.datamicroscope.core.condition;

import com.alibaba.fastjson.JSONObject;
import com.minelx.datamicroscope.core.values.CommonField;

import java.util.List;
import java.util.Objects;

import static java.util.Collections.singletonList;

public class KeyOperandCondition implements Condition {

	private final CommonField key;

	private final Operand operand;

	private KeyOperandCondition(CommonField key, Operand operand) {
		this.key = key;
		this.operand = operand;
	}

	@Override
	public String sqlText() {
		return operand.sqlOf(key);
	}

	@Override
	public List<CommonField> containedFields() {
		return singletonList(key);
	}

	public Operand operand() {
		return operand;
	}

	public JSONObject toJSON() {
		JSONObject result = new JSONObject();
		result.put("key", key.path());
		result.putAll(operand.toJSON());
		return result;
	}

	public static KeyOperandCondition of(CommonField key, Operand operand) {
		return new KeyOperandCondition(key, operand);
	}

	public static KeyOperandCondition from(JSONObject data) {
		CommonField key = CommonField.from(data.getString("key"));
		return new KeyOperandCondition(key, Operand.from(data));
	}

	@Override
	public boolean equals(Object o) {
		if (this == o) return true;
		if (o == null || getClass() != o.getClass()) return false;
		KeyOperandCondition condition = (KeyOperandCondition) o;
		return operand.equals(condition.operand) && key.equals(condition.key);
	}

	@Override
	public int hashCode() {
		return Objects.hash(operand, key);
	}
}
